<script setup lang="ts">
  import { computed, ref } from 'vue'
  import useGetGoodTypeOptions from '@/services/pages/common/good-type-options'
  import { FormInstance } from 'element-plus'
  import _ from 'lodash'

  const { goodTypeOptions, getGoodTypeOptionsLoading, getGoodTypeOptions } = useGetGoodTypeOptions()

  defineOptions({
    name: 'BaseInfoWarrantyPolicyCreate',
  })

  const props = defineProps({
    isNameRepeat: {
      type: Boolean,
      default: () => false,
    },
  })

  // 表单校验规则
  const rules = ref({
    name: [{ required: true, message: '保修政策名称不能为空', trigger: ['blur', 'change'] }],
    goodsTypeVos: [{ required: true, message: '请选择关联设备分类', trigger: ['blur', 'change'] }],
    mobileShow: [{ required: true, message: '请选择移动端是否显示', trigger: ['blur', 'change'] }],
  })
  const getGoodTypeKeyword = ref('')

  // 二级设备分类
  const secondGoodTypeOptions = computed(() => {
    let result: Array<GoodTypeOptions> = []

    goodTypeOptions.value.forEach((goodTypeOptions) => {
      result.push(...goodTypeOptions.childData)
    })

    result = result.filter((secondGoodType) =>
      secondGoodType.name.includes(getGoodTypeKeyword.value),
    )

    return result
  })

  // 表单
  const form = ref<GoodAPIRequest.SaveGoodWarrantyPolicy>({
    descr: '',
    goodsTypeVos: [],
    id: '',
    mobileShow: true,
    name: '',
    status: false,
  })

  // 设备分类
  const goodTypes = ref<Array<string>>([])

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  const handleGetGoodType = _.debounce((keyword: string) => {
    getGoodTypeKeyword.value = keyword
  }, 600)

  /**
   * 根据二级分类id查找一级分类
   * @param {String} id - 二级分类id
   */
  const findFirstGoodType = (id: string) => {
    return goodTypeOptions.value.find((firstGoodType) => {
      const secondGoodTypeIds = firstGoodType.childData.map((item) => item.id)
      return secondGoodTypeIds.includes(id)
    })
  }

  /**
   * 设备分类选择事件
   */
  const handleGoodTypeChange = () => {
    form.value.goodsTypeVos = goodTypes.value.map((secondGoodTypeId) => {
      return {
        goodsOneTypeId: findFirstGoodType(secondGoodTypeId).id,
        goodsTwoTypeId: secondGoodTypeId,
      }
    })
  }

  defineExpose({
    getGoodTypeOptions,
    getForm: async () => {
      if (formInstance.value) {
        try {
          await formInstance.value.validate()
          return {
            name: form.value.name,
            mobileShow: form.value.mobileShow,
            status: form.value.status,
            id: form.value.id,
            descr: form.value.descr,
            goodsTypeVos: _.cloneDeep(form.value.goodsTypeVos),
          }
        } catch (error) {
          return
        }
      }
    },
    setForm: (baseInfo: GoodAPIRequest.SaveGoodWarrantyPolicy) => {
      form.value = {
        name: baseInfo.name,
        descr: baseInfo.descr,
        id: baseInfo.id,
        status: baseInfo.status,
        mobileShow: baseInfo.mobileShow,
        goodsTypeVos: _.cloneDeep(baseInfo.goodsTypeVos),
      }
      goodTypes.value = baseInfo.goodsTypeVos.map((item) => item.goodsTwoTypeId)
    },
    resetForm: () => {
      form.value = {
        descr: '',
        goodsTypeVos: [],
        id: '',
        mobileShow: false,
        name: '',
        status: false,
      }
    },
  })
</script>

<template>
  <div class="base-info-warranty-policy-create">
    <div class="title">基本信息</div>
    <el-form ref="formInstance" label-width="106" :rules="rules" inline-message :model="form">
      <el-form-item label="保修政策名称" prop="name">
        <el-input
          v-model.trim="form.name"
          placeholder="请输入保修政策名称"
          :class="{ 'warranty-policy-name-fail': props.isNameRepeat }"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="关联设备分类" prop="goodsTypeVos">
        <el-select
          v-model="goodTypes"
          :loading="getGoodTypeOptionsLoading"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="2"
          placeholder="请选择设备分类"
          filterable
          :filter-method="handleGetGoodType"
          @change="handleGoodTypeChange"
        >
          <el-option
            v-for="(goodTypeOption, goodTypeOptionIndex) in secondGoodTypeOptions"
            :key="goodTypeOptionIndex"
            :label="goodTypeOption.name"
            :value="goodTypeOption.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="整机保修描述" prop="descr">
        <el-input
          v-model.trim="form.descr"
          placeholder="如整机保修xx年"
          maxlength="15"
          resize="both"
        />
      </el-form-item>
      <el-form-item label="移动端是否显示" prop="mobileShow">
        <el-radio-group v-model="form.mobileShow">
          <el-radio :value="true" size="small">显示</el-radio>
          <el-radio :value="false" size="small">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" props="status">
        <el-radio-group v-model="form.status">
          <el-radio :value="false" size="small">启用</el-radio>
          <el-radio :value="true" size="small">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
  .base-info-warranty-policy-create {
    display: flex;
    flex-direction: column;
    row-gap: 12px;

    .title {
      font-size: 12px;
      font-weight: bold;
      padding-left: 6px;
      border-left: 3px solid $primaryColor;
    }

    :deep(.el-form) {
      padding: 0 12px;
      box-sizing: border-box;
      display: flex;
      column-gap: 84px;
      flex-wrap: wrap;
      row-gap: 12px;

      .el-form-item {
        .el-form-item__label {
          height: 28px;
          line-height: 28px;
        }

        .el-form-item__content {
          align-items: flex-start;
          flex-direction: column;

          .warranty-policy-name-fail {
            .el-input__wrapper {
              box-shadow: 0 0 0 1px $deleteColor inset;
            }
          }

          .el-form-item__error {
            padding: 0;
            margin: 3px 0 0 0;
          }

          .el-input,
          .el-select {
            width: 270px;
          }

          .el-radio-group {
            column-gap: 12px;

            .el-radio {
              margin: 0;
              height: 28px;
              column-gap: 5px;

              .el-radio__label {
                padding: 0;
                height: 28px;
                line-height: 28px;
              }
            }
          }

          .el-select__selection {
            flex-wrap: nowrap;

            .el-select__tags-text {
              display: inline-block;
              max-width: 50px;

              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .el-textarea {
            width: fit-content;

            .el-textarea__inner {
              min-width: 270px !important;
              max-width: 730px !important;
              height: 28px;
              min-height: 28px !important;
              max-height: 85px !important;
            }
          }
        }
      }
    }
  }
</style>
